<template>
	<view class="container">
		<!-- 时间查询条件 -->
		<view class="time-filter" v-if="type<10">
			<view class="filter-item" @click="showTimePopup = true">
				<view class="filter-text">{{selectedTimeText}}</view>
				<u-icon name="arrow-down" size="24" color="#666"></u-icon>
			</view>
		</view>
		<view class="wrap" :style="type < 10 ? 'margin-top: 100rpx;' : ''">
			<!-- <view class="search">
				<u-search v-model="keywords" @custom="search" @search="search"></u-search>
			</view> -->
			<scroll-view class="scroll-list" scroll-y="true" @scrolltolower="loadMore">
				<u-cell-group class="list" :border="false">
					<u-swipe-action class="list-item" :options="options" v-for="(item, index) in list" :key="item.id" :index="index" @click="optionsClick">
						<u-cell-item :arrow="true" @click="navTo('addBustogether?item='+JSON.stringify(item)+'&type='+type)">
							<text slot="title">{{item.mainName}}</text>
							<text slot="label">
								<view>
									<text>金额：{{item.quantity}}{{item.unit == '01' ? '元' : '张'}}</text>
									<text>{{item.ownOfficeName == '' ? '':('本店店铺：'+ item.ownOfficeName)}}</text>
								</view>
								<view>
									<text>{{item.subType == 'KZ' ? '发生日期':'销售日期'}}：{{item.startSaleDate}}</text>
									<text>{{item.officeName == '' ? '':('分店名称：'+item.officeName)}}</text>
								</view>
							</text>
						</u-cell-item>
					</u-swipe-action>
				</u-cell-group>
				<view class="loadmore" @click="loadMore">
					<u-loadmore :status="loadStatus"></u-loadmore>
				</view>
			</scroll-view>
			<view class="btn-plus" v-if="type < 10" @click="navTo('addBustogether?type='+type)">
				<u-icon name="plus-circle-fill" size="90" color="#3d87ff"></u-icon>
			</view>
		</view>
		<!-- 时间选择弹窗 -->
		<u-popup v-model="showTimePopup" mode="bottom" border-radius="0">
			<view class="time-popup">
				<view class="popup-header">
					<view class="title">请选择时间范围</view>
				</view>
				<view class="popup-content">
					<view class="time-option" 
						v-for="(item, index) in timeOptions" 
						:key="index"
						@click="selectTimeOption(item)">
						<view class="option-text">{{item.label}}</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- 自定义时间选择弹窗 -->
		<u-popup v-model="showCustomDatePopup" mode="bottom" border-radius="0">
			<view class="date-picker-popup">
				<view class="date-header">请选择时间范围</view>
				<view class="date-display">{{tempStartDate}}~{{tempEndDate}}</view>
				<view class="date-tabs">
					<view class="tab-item" :class="{'active': isSelectingStart}" @click="switchToStart">
						<text>{{tempStartDate}} 开始</text>
					</view>
					<view class="tab-item" :class="{'active': !isSelectingStart}" @click="switchToEnd">
						<text>{{tempEndDate}} 结束</text>
					</view>
				</view>
				<view class="picker-labels">
					<text class="label-item">年</text>
					<text class="label-item">月</text>
					<text class="label-item">日</text>
				</view>
				<view class="picker-container">
					<picker-view class="picker-view" :indicator-style="indicatorStyle" :value="pickerValue" @change="onPickerChange">
						<picker-view-column>
							<view class="picker-item" v-for="year in years" :key="year">{{year}}</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="month in months" :key="month">{{month.padStart(2, '0')}}</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="day in days" :key="day">{{day.padStart(2, '0')}}</view>
						</picker-view-column>
					</picker-view>
				</view>
				<view class="picker-actions">
					<view class="picker-btn cancel" @click="cancelDatePicker">取消</view>
					<view class="picker-btn confirm" @click="confirmDatePicker">完成</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
export default {
	data() {
		return {
			type:1,
			keywords: '',
			query: {
				pageNo: 1,
				pageSize: 20,
				subType:'',
				ownOfficeCode:'',
				startSaleDate:'',
				endSaleDate:'',
				mainType:'',
			},
			list: [],
			count: 0,
			loadStatus: 'loadmore',
			options: [
				{text: '删除', style: { background: '#dd524d'}},
				// {text: '上传', style: { background: '#414ee0'}},
			],
			mainTypeList:[],
			// 时间筛选相关
			showTimePopup: false,
			showCustomDatePopup: false,
			selectedTimeOption: 'month',
			timeOptions: [
				{ label: '全部', value: 'all' },
				{ label: '今日', value: 'today' },
				{ label: '昨日', value: 'yesterday' },
				{ label: '本月', value: 'month' },
				{ label: '上个月', value: 'lastMonth' },
				{ label: '其它时间', value: 'custom' }
			],
			startDate: '',
			endDate: '',
			minDate: '2020-01-01',
			maxDate: new Date().toISOString().split('T')[0],
			// 时间选择器相关
			pickerValue: [2, 3, 1], // 默认选中值
			years: [], // 年份选项
			months: [], // 月份选项
			days: [], // 日期选项
			tempStartDate: '', // 临时开始日期
			tempEndDate: '', // 临时结束日期
			isSelectingStart: true, // 是否正在选择开始日期
			indicatorStyle: 'height: 80rpx; border-top: 1px solid #e5e5e5; border-bottom: 1px solid #e5e5e5;',
		};
	},
	computed: {
		selectedTimeText() {
			const option = this.timeOptions.find(item => item.value === this.selectedTimeOption);
			if (this.selectedTimeOption === 'custom' && this.startDate && this.endDate) {
				return `${this.startDate} 至 ${this.endDate}`;
			}
			return option ? option.label : '本月';
		}
	},
	onLoad(params) {
		this.type = params.type
		// 设置页面标题
		let title = ''
		if(this.type == 1){
			title = '合买'
			this.query.subType = 'HM'
		}else if(this.type == 2){
			title = '帮分店出票'
			this.query.subType = 'BFD'
		}else if(this.type == 3){
			title = '给分店出票'
			this.query.subType = 'GFD'
		}else if(this.type == 4){
			title = '本店销量'
			this.query.subType = 'BDXL'
		}else if(this.type == 5){
			title = '体彩'
			this.query.subType = 'YJ'
			this.query.mainType = '10'
		}else if(this.type == 6){
			title = '福彩'
			this.query.subType = 'YJ'
			this.query.mainType = '09'
		}else if(this.type == 7){
			title = '刮刮乐'
			this.query.subType = 'YJ'
			this.query.mainType = '11'
		}else if(this.type == 8){
			title = '其他'
			this.query.subType = 'YJ'
			this.query.mainType = '13'
		}else if(this.type == 9){
			title = '开支录入'
			this.query.subType = 'KZ'
		}else if(this.type == 10){
			title = '销售报表详情'
			this.query.subType = 'BDXL,BFD,GFD'
			if(params.item){
				let itemDetail = JSON.parse(params.item)
				this.query.ownOfficeCode = itemDetail.ownOfficeCode
				this.query.startSaleDate = itemDetail.startSaleDate
				this.query.endSaleDate = itemDetail.startSaleDate
			}
		}else if(this.type == 11){
			title = '分店出票详情'
			this.query.subType = 'BFD,GFD'
			if(params.item){
				let itemDetail = JSON.parse(params.item)
				this.query.ownOfficeCode = itemDetail.ownOfficeCode
				this.query.startSaleDate = itemDetail.startSaleDate
				this.query.endSaleDate = itemDetail.endSaleDate
				this.query.officeName = itemDetail.officeName
			}
		}else if(this.type == 12){
			title = '合买出票详情'
			this.query.subType = 'HM'
			if(params.item){
				let itemDetail = JSON.parse(params.item)
				this.query.ownOfficeCode = itemDetail.ownOfficeCode
				this.query.startSaleDate = itemDetail.startSaleDate
				this.query.endSaleDate = itemDetail.startSaleDate
			}
		}else if(this.type == 13){
			title = '佣金详情'
			this.query.subType = 'YJ'
			if(params.item){
				let itemDetail = JSON.parse(params.item)
				this.query.ownOfficeCode = itemDetail.ownOfficeCode
				this.query.startSaleDate = itemDetail.startSaleDate
				this.query.endSaleDate = itemDetail.startSaleDate
			}
		}else if(this.type == 14){
			title = '开支详情'
			this.query.subType = 'KZ'
			if(params.item){
				let itemDetail = JSON.parse(params.item)
				this.query.ownOfficeCode = itemDetail.ownOfficeCode
				this.query.startSaleDate = itemDetail.startSaleDate
				this.query.endSaleDate = itemDetail.startSaleDate
			}
		}
		uni.setNavigationBarTitle({
			title: title
		});
		// 设置默认时间范围
		this.setDefaultTimeRange();
		// 主类型
		this.$u.api.mainType.treeData({dictType:'sale_main_type'}).then(res => {
			this.mainTypeList = res;
			this.loadList();
		});
	},
	onShow() {
		if (uni.getStorageSync('refreshList') === true){
			uni.removeStorageSync('refreshList');
			this.search('');
		}
	},
	methods: {
		findNameByValue(array, value) {
		    const foundObject = array.find(item => item.dictValue == value);
		    return foundObject ? foundObject.dictLabel : null;
		},
		loadMore() {
			this.loadStatus = "loading";
			setTimeout(() => {
				this.query.pageNo += 1;
				this.loadList();
			}, 100);
		},
		loadList() {
			let that = this
			// 添加时间范围到查询条件
			if(that.type < 10){
				this.query.startSaleDate = this.startDate;
				this.query.endSaleDate = this.endDate;
			}
			this.$u.api.salesManagement.list(this.query).then(res => {
				if (!res.list || res.list.length == 0){
					this.loadStatus = "nomore";
					return;
				}
				res.list.forEach(function(e) {
					e.mainName = that.findNameByValue(that.mainTypeList, e.mainType);
				});
				this.list = this.list.concat(res.list);
				this.count = res.count;
				this.query.pageNo = res.pageNo;
				this.query.pageSize = res.pageSize;
				this.loadStatus = "loadmore";
			});
		},
		optionsClick(rowIndex, btnIndex) {
			let self = this, row = self.list[rowIndex];
			if(btnIndex == 1) {
				this.navTo('formUpload?id='+row.id);
			} else if(btnIndex == 0) {
				if(row.status == 9 || row.status == 4){
					this.$u.toast('该状态不能删除！');
					return;
				}
				if(row.mainType == '11' || row.mainType == '29' || row.mainType == '30' || row.mainType == '31'){
					this.$u.toast('该类型不能删除！');
					return;
				}
				// 检查是否为两个月前的数据
				if(!this.isWithinTwoMonths(row.startSaleDate)){
					this.$u.toast('不能删除两个月前的数据！');
					return;
				}
				uni.showModal({
					title: '提示',
					content: '确认要删除该数据吗？',
					showCancel: true,
					success: function (res2) {
						if (res2.confirm) {
							self.$u.api.salesManagement.delete({id: row.id}).then(res => {
								self.$u.toast(res.message);
								if (res.result == 'true'){
									self.list.splice(rowIndex, 1);
								}
							});
						}
					}
				});
			}
		},
		search(value) {
			this.list = [];
			this.query.pageNo = 1;
			// this.query.testInput = value;
			this.loadList();
		},
		navTo(url) {
			uni.navigateTo({
				url: url
			});
		},
		setDefaultTimeRange() {
			const now = new Date();
			const year = now.getFullYear();
			const month = now.getMonth();
			const date = now.getDate();
			
			switch (this.selectedTimeOption) {
				case 'all':
					// 全部时间，设置为最早时间到当前时间
					this.startDate = this.minDate;
					this.endDate = this.maxDate;
					break;
				case 'today':
					// 今天
					this.startDate = this.formatDate(now);
					this.endDate = this.formatDate(now);
					break;
				case 'yesterday':
					// 昨天
					const yesterday = new Date(now);
					yesterday.setDate(date - 1);
					this.startDate = this.formatDate(yesterday);
					this.endDate = this.formatDate(yesterday);
					break;
				case 'month':
					// 本月
					this.startDate = `${year}-${String(month + 1).padStart(2, '0')}-01`;
					this.endDate = this.formatDate(now);
					break;
				case 'lastMonth':
					// 上个月
					const lastMonth = new Date(year, month - 1, 1);
					this.startDate = `${year}-${String(month).padStart(2, '0')}-01`;
					// 获取上个月的最后一天
					const lastDayOfLastMonth = new Date(year, month, 0).getDate();
					this.endDate = `${year}-${String(month).padStart(2, '0')}-${lastDayOfLastMonth}`;
					break;
				case 'custom':
					// 自定义时间，保持原有值
					break;
			}
			
			// 更新查询条件
			if(this.type < 10){
				this.query.startSaleDate = this.startDate;
				this.query.endSaleDate = this.endDate;
			}
		},
		selectTimeOption(item) {
			this.selectedTimeOption = item.value;
			if (item.value === 'custom') {
				this.showTimePopup = false;
				this.isSelectingStart = true;
				// 初始化日期选择器
				this.initDatePicker();
				// 设置临时日期
				this.tempStartDate = this.startDate || this.formatDate(new Date());
				this.tempEndDate = this.endDate || this.formatDate(new Date());
				// 设置开始日期的picker值
				const startDate = new Date(this.tempStartDate);
				this.setPickerValue(startDate);
				this.showCustomDatePopup = true;
			} else {
				this.setDefaultTimeRange(item.value);
				this.showTimePopup = false;
				this.search();
			}
		},
		switchToStart() {
			this.isSelectingStart = true;
			// 设置当前选中的日期对应的 picker 值
			const startDate = this.tempStartDate ? new Date(this.tempStartDate) : new Date();
			this.setPickerValue(startDate);
		},
		switchToEnd() {
			this.isSelectingStart = false;
			// 设置当前选中的日期对应的 picker 值
			const endDate = this.tempEndDate ? new Date(this.tempEndDate) : new Date();
			this.setPickerValue(endDate);
		},
		setPickerValue(date) {
			const yearIndex = this.years.findIndex(year => year === date.getFullYear());
			const monthIndex = date.getMonth(); // 月份从0开始
			const dayIndex = date.getDate() - 1; // 日期从1开始
			this.pickerValue = [yearIndex, monthIndex, dayIndex];
		},
		initDatePicker() {
			// 生成年份选项（前5年到后5年）
			const currentYear = new Date().getFullYear();
			this.years = [];
			for (let i = currentYear - 5; i <= currentYear + 5; i++) {
				this.years.push(i);
			}
			
			// 生成月份选项 (1-12)
			this.months = Array.from({length: 12}, (_, i) => String(i + 1));
			
			// 生成日期选项
			this.updateDays();
			
			// 设置默认值为当前日期
			const now = new Date();
			this.setPickerValue(now);
		},
		updateDays() {
			const year = this.years[this.pickerValue[0]];
			const month = parseInt(this.months[this.pickerValue[1]]);
			const daysInMonth = new Date(year, month, 0).getDate();
			this.days = Array.from({length: daysInMonth}, (_, i) => String(i + 1));
		},
		onPickerChange(e) {
			this.pickerValue = e.detail.value;
			this.updateDays();
			
			const year = this.years[this.pickerValue[0]];
			const month = this.months[this.pickerValue[1]].padStart(2, '0');
			const day = this.days[this.pickerValue[2]].padStart(2, '0');
			const dateStr = `${year}-${month}-${day}`;
			
			if (this.isSelectingStart) {
				this.tempStartDate = dateStr;
			} else {
				this.tempEndDate = dateStr;
			}
		},
		cancelDatePicker() {
			this.showCustomDatePopup = false;
			// 重置临时日期
			this.tempStartDate = this.startDate;
			this.tempEndDate = this.endDate;
			this.isSelectingStart = true;
		},
		confirmDatePicker() {
			const startDate = new Date(this.tempStartDate);
			const endDate = new Date(this.tempEndDate);
			
			if (!this.isSelectingStart && endDate < startDate) {
				uni.showToast({
					title: '结束日期不能早于开始日期',
					icon: 'none'
				});
				return;
			}
			
			this.startDate = this.tempStartDate;
			this.endDate = this.tempEndDate;
			this.showCustomDatePopup = false;
			this.search();
		},
		formatDate(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		},
		// 检查日期是否在最近两个月内
		isWithinTwoMonths(recordDate) {
			if (!recordDate) return false;
			
			const today = new Date();
			const currentYear = today.getFullYear();
			const currentMonth = today.getMonth() + 1; // getMonth() 返回 0-11，需要 +1
			
			// 解析记录日期
			const recordDateObj = new Date(recordDate);
			const recordYear = recordDateObj.getFullYear();
			const recordMonth = recordDateObj.getMonth() + 1;
			
			// 计算最近两个月的范围
			let allowedMonths = [];
			for (let i = 0; i < 2; i++) {
				const month = currentMonth - i;
				const year = month < 0 ? currentYear - 1 : currentYear;
				allowedMonths.push({ year, month: month < 0 ? month + 12 : month });
			}
			
			const isWithinTwoMonths = allowedMonths.some(({ year, month }) => 
				recordYear === year && recordMonth === month
			);
			
			return isWithinTwoMonths;
		},
	}
};
</script>
<style lang="scss">
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	// padding: 20rpx;
	box-sizing: border-box;
}
page {
	background-color: #f8f8f8;
}
.btn-plus {
	position: absolute;
	bottom: 50rpx;
	right: 50rpx;
	z-index: 1;
	opacity: 0.6;
}
.btn-plus:hover {
	opacity: 1;
}.list {
	.list-item {
		position: relative;
		view {
			display: flex;
			justify-content: space-between;
			
			text {
				flex: 0 0 50%;
				text-align: left;
			}
		}
		&::after {
			content: '';
			position: absolute;
			left: 30rpx;
			right: 30rpx;
			bottom: 0;
			height: 1rpx;
			background-color: #D7DEEB;
		}
		&:last-child::after {
			display: none;
		}
	}
}
.time-filter {
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1px solid #eee;
	position: fixed;
    width: 100%;
    z-index: 9999;
	
	.filter-item {
		display: flex;
		align-items: center;
		height: 70rpx;
		padding: 0 20rpx;
		
		.filter-text {
			margin-right: 10rpx;
			font-size: 28rpx;
			color: #333;
		}
	}
}

.time-popup {
	background-color: #fff;
	
	.popup-header {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-bottom: 1rpx solid #eee;
		
		.title {
			font-size: 32rpx;
			color: #333;
		}
	}
	
	.popup-content {
		.time-option {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-bottom: 1rpx solid #eee;
			
			.option-text {
				font-size: 30rpx;
				color: #333;
			}
			
			&:active {
				background-color: #f5f5f5;
			}
		}
	}
}

.date-picker-popup {
	background-color: #fff;
	
	.date-header {
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		font-size: 32rpx;
		color: #333;
		border-bottom: 1px solid #eee;
	}
	
	.date-display {
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
		color: #2979ff;
		border-bottom: 1px solid #eee;
	}
	
	.date-tabs {
		display: flex;
		height: 80rpx;
		background: #fff;
		border-bottom: 1px solid #eee;
		
		.tab-item {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			color: #666;
			position: relative;
			
			&.active {
				color: #2979ff;
				
				&::after {
					content: '';
					position: absolute;
					left: 0;
					bottom: 0;
					width: 100%;
					height: 2px;
					background-color: #2979ff;
				}
			}
		}
	}
	
	.picker-labels {
		height: 80rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		background-color: #f8f8f8;
		border-bottom: 1px solid #eee;
		
		.label-item {
			flex: 1;
			text-align: center;
			font-size: 28rpx;
			color: #666;
		}
	}
	
	.picker-container {
		height: 400rpx;
		position: relative;
		
		.picker-view {
			width: 100%;
			height: 100%;
		}
		
		.picker-item {
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			font-size: 32rpx;
			color: #333;
		}
	}
	
	.picker-actions {
		display: flex;
		height: 100rpx;
		border-top: 1px solid #eee;
		
		.picker-btn {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
			
			&.cancel {
				color: #333;
				background-color: #fff;
				border-right: 1px solid #eee;
			}
			
			&.confirm {
				color: #fff;
				background-color: #2979ff;
			}
		}
	}
}
/deep/ .list .u-cell-item-box .u-cell_title{
	display: flex;
	flex-direction: column;
}
</style>
